package cn.dapeng.thread;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.TimeUnit;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread
 * @Description 启动两个线程，一个干完，另一个再干
 *  * 线程间通信例子  使用wait、notifyAll实现
 * @ClassName ThreadCommunicationT02
 * @Author xupenghong
 * @Date 2024/8/28 11:04
 * @Version 1.0.0
 */
public class ThreadCommunicationT02 {

    public static int sept = -1;
    public static boolean running = true;
    public static String str = "1A2B3C4D";
    public final static Object monitor = new Object();

    public static void main(String[] args) {

        char[] chars = str.toCharArray();

        new Thread(() -> {
            while (true) {
                synchronized (monitor) {
                    if (running) {
                        int index = getIndex(chars.length);
                        System.out.print(Thread.currentThread().getName() + " : ");
                        System.out.println(chars[index]);
                        running = false;
                        SleepingUtil.sleep(1, TimeUnit.SECONDS);
                        monitor.notifyAll();
                    } else {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }

        }).start();

        new Thread(() -> {
            while (true) {
                synchronized (monitor) {
                    if (!running) {
                        int index = getIndex(chars.length);
                        System.out.print(Thread.currentThread().getName() + " : ");
                        System.out.println(chars[index]);
                        running = true;
                        SleepingUtil.sleep(10, TimeUnit.MILLISECONDS);
                        monitor.notifyAll();
                    } else {

                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }

                }
            }
        }).start();
    }

    public static int getIndex(int size) {
        sept++;
        if (sept == size) {
            sept = 0;
        }
        return sept;
    }

}
